﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Modeling.Common;
using Microsoft.Practices.Modeling.Common.Design;
using Microsoft.Practices.Modeling.Common.Security;
using Microsoft.Practices.Modeling.Common.Utility;
using Microsoft.Practices.Modeling.ExtensionProvider.Utility;
//using Microsoft.Practices.Modeling.Services.Properties;
using Microsoft.Practices.Services.ItineraryDsl;
using Microsoft.VisualStudio.Modeling;
using System.CodeDom;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;
using Microsoft.Practices.Modeling.Services.Design;
using Microsoft.Practices.Modeling.ExtensionProvider.Extension;
using System.IO;
using System.Globalization;
using System.Xml;

namespace BizTalk.ESB.Extensions.ResolverExtenders
{
    public class BamTrackingExtenderUtility
    {
        public static void SyncBamResolverExtender(StaticBamTrackingResolverExtender ResolverExtenderInstance)
        {
            var bamNameXpath = @"/*[local-name()='BAMDefinition']/*[local-name()='Activity']/@*[local-name()='Name']";
            IObjectExtender ext = ResolverExtenderInstance as IObjectExtender;
            if (((ResolverExtenderInstance != null) && (ext != null)) && (ext.ModelElement != null))
            {
                if (ResolverExtenderInstance.BamActivityDefinitionFile != null)
                {
                    string path = ResolverExtenderInstance.BamActivityDefinitionFile;
                    if (!Path.IsPathRooted(path))
                    {
                        path = RuntimeHelper.GetExecutionPath(path);
                    }
                    if (!File.Exists(path))
                    {
                        throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, "BAM Activity Definition File not found: {0}", new object[] { path }));
                    }
                    var bamDefinitionName = BamTrackingExtenderUtility.GetBamActivityName(path, bamNameXpath);
                    using (Transaction transaction = ext.ModelElement.Store.TransactionManager.BeginTransaction("ResetBamResolverExtender"))
                    {
                        ResolverExtenderInstance.BamActivityDefinitionName = bamDefinitionName;
                        transaction.Commit();
                    }
                }
            }
        }

        private static string GetBamActivityName(string BamDefinitionXmlFile, string bamActivityNameXpath)
        {
            var bamName = string.Empty;
            var bamXmlFile = new XmlDocument();
            bamXmlFile.Load(BamDefinitionXmlFile);

            bamName = bamXmlFile.SelectSingleNode(bamActivityNameXpath).Value;

            return bamName;
        }
    }
}
